// 添加axios引用
import axios from 'axios'
import md5 from 'js-md5'

const isProduction = process.env.NODE_ENV == 'production'
const baseURL = isProduction ? 'https://python.jiahu.tech' : '/api'

// 通用配置
const defaultHeaders = {
	'Content-Type': 'application/json',
	Authorization: 'Bearer pat_j9WL0ZaCLg3vBkIjAxYMtZGWCKusJdS6RFzOgZkyzCc41JlKjOBATz4MJTWtOkJP'
}

// 创建实例
function createInstance() {
	const instance = axios.create({
		baseURL,
		timeout: 120000,
		headers: defaultHeaders
	})

	// 请求拦截
	instance.interceptors.request.use(config => {
		const token = localStorage.getItem('token')
		if (token) {
			config.headers.Authorization = `Bearer ${token}`
		}

		let timestamp = new Date().getTime()
		let secret_key = '829a56cc8ffa56209e3a10b80d0bbdf8'
		let signature = md5(`${secret_key}${timestamp}`)
		if (config.method === 'get') {
			config.params = {
				...config.params, // 保留原有params
				timestamp,
				signature
			}
		} else {
			config.data = {
				...config.data, // 保留原有data
				timestamp,
				signature
			}
		}
		return config
	})

	// 响应拦截
	instance.interceptors.response.use(
		response => response.data,
		error => {
			if (error.response) {
				const { status, data } = error.response
				return Promise.reject({
					code: status,
					message: data?.message || `请求失败 (${status})`,
					data
				})
			}
			return Promise.reject(error)
		}
	)

	return instance
}

// 核心请求方法
async function request(config) {
	const instance = createInstance()
	try {
		return await instance.request(config)
	} catch (error) {
		console.error('Request error:', error)
		throw error
	}
}

// 快捷方法
export default {
	get(url, params) {
		return request({ method: 'get', url, params })
	},
	post(url, data) {
		return request({ method: 'post', url, data })
	},
	put(url, data) {
		return request({ method: 'put', url, data })
	},
	delete(url) {
		return request({ method: 'delete', url })
	}
}
